// pages/myduration/myduration.js
const app = getApp()
var request = require("../../utils/request.js");
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    remainTime: 0,
    ruleId: '',
    money: 0,
    list: [],
    checkIndex: 0,
    windowHeight: 0,
    scrollViewHeight: 0,
    parkList: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    // 先取出页面高度 windowHeight
    that.setData({
      windowHeight: wx.getSystemInfoSync().windowHeight
    });
    let scrollViewHeight = that.data.windowHeight - that.data.statusBarHeight - 44 - 178;
    that.setData({
      scrollViewHeight: scrollViewHeight
    })
    let remainTime = options.remainTime;
    if (remainTime != '' && remainTime != undefined) {
      that.setData({
        remainTime: remainTime
      })
    }
    that.getTimeList();
  },
  /**
   * 选择不同的套餐
   * @param {*} event 
   */
  selectItem(event) {
    let index = event.currentTarget.dataset.index;
    let that = this;
    let list = that.data.list;
    for (let i = 0; i < list.length; i++) {
      if (i == index) {
        list[i].seleted = true;
      } else {
        list[i].seleted = false;
      }
    }
    that.setData({
      list: list,
      checkIndex: index
    })
  },
  /**
   * 和服务器发起支付申请
   */
  miniPay() {
    let that = this;
    let list = that.data.list;
    let checkIndex = that.data.checkIndex;
    let userId = wx.getStorageSync('userId');
    let body = '充值时长';
    let totalFee = list[checkIndex].moneys;
    let ruleId = list[checkIndex].ruleId;
    let duration = list[checkIndex].hours;
    let parkId = that.data.parkId;
    let url = "/api/pay/elecardMiniPayV2?uid=" + userId + "&body=" + body + "&totalFee=" + totalFee + '&ruleId=' + ruleId + "&CarCardNum=0" + "&duration=" + duration + "&startTime=0" + "&type=1";
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          if (res.data.data != null) {
            let body = res.data.data;
            wx.requestPayment({
              timeStamp: res.data.data.timeStamp,
              nonceStr: res.data.data.nonceStr,
              package: res.data.data.package,
              signType: 'MD5',
              paySign: res.data.data.paySign,
              success(res) {
                wx.showToast({
                  title: '支付成功',
                  icon: 'success',
                  duration: 1500,
                })
                var timeOut = setTimeout(function () {
                  that.getUserInfo(userId);
                }, 2000)

              },
              fail(res) {
                // Toast.fail('支付失败');
                console.log(res)
              }
            })
          }
        }
      })
      .catch((errMsg) => {  });
  },
  /**
   * 获取时长套餐
   */
  getTimeList() {
    let that = this;
    let url = "/api/bRechargeRule/selectByRuleType";
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let list = res.data.data.rule;
          if (list != null && list.length > 0) {
            for (let i = 0; i < list.length; i++) {
              if (i == 0) {
                list[i].seleted = true;
              } else {
                list[i].seleted = false;
              }
            }
            that.setData({
              list: list
            })
          }
        }
      })
      .catch((errMsg) => {
        // wx.showToast({
        //   title: '暂无数据',
        //   icon: 'loading',
        //   duration: 1000,
        // })
      });
  },
  /**
   * 获取用户信息
   * @param {String} userId 用户ID
   */
  getUserInfo(userId) {
    let that = this;
    let url = "/api/cUser/myInfo?userId=" + userId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          that.setData({
            remainTime: res.data.data.remainTime
          })
        } else {
          Toast.fail(res.data.message);
        }
      })
  },
  //支付回调
  // payCallBack(body) {
  //   let that = this;
  //   let userId = wx.getStorageSync('userId');
  //   let url = "/api/pay/wechat/eleCardCallback";
  //     request.http(url, 'POST', params).then((res) => {
  //       if (res.data.status == 200) {
  //         that.getUserInfo(userId);
  //       } else {
  //         Toast.fail('支付回调失败');
  //       }
  //     })
  // },
  /**
   * 选择停车场
   * @param {*} event 
   */
  bindParkChange(event) {
    let index = event.detail.value;
    let that = this;
    let parkNameList = that.data.parkNameList;
    let parkId = that.data.parkList[index].parkId;
    let parkName = parkNameList[index];
    let parkCode = that.data.parkList[index].parkCode;
    that.setData({
      parkName: parkName,
      parkId: parkId,
      parkCode: parkCode
    })
    that.getParkRule(parkId);
  },
  /**
   * 获取有可售时长的停车场
   */
  getParks() {
    let that = this;
    let url = "/api/sPlatRechargeRecord/getRemainLengthParks";
    request.http(url, 'POST')
      .then((res) => {
        wx.hideLoading();
        if (res.data.code == 200) {
          let parkList = res.data.data;
          if (parkList != null && parkList.length > 0) {
            that.setData({
              parkList: parkList
            })
          } else {
            Toast(res.data.message);
            that.setData({
              parkList: []
            })
          }
        } else {
          Toast.fail(res.data.message);
        }
      })
  },
  /**
   * 根据不同停车场获取不同时长
   */
  getParkTimes() {
    let that = this;
    let userId = wx.getStorageSync('userId');
    let parkId = that.data.parkId;
    let url = "/api/cUser/park/remaintime?userId=" + userId + "&parkId=" + parkId;
    request.http(url, 'POST')
      .then((res) => {
        if (res.data.code == 200) {
          let remainTime = res.data.data;
          if (remainTime != null && remainTime != undefined) {
            that.setData({
              remainTime: remainTime
            })
          } else {
            Toast(res.data.message);
            that.setData({
              remainTime: 0
            })
          }
        } else {
          Toast.fail(res.data.message);
        }
      })
  }
})